package com.baizhi.aspect;

import com.baizhi.annotation.AdminLogAnnotation;
import com.baizhi.dao.CmfzLogMapper;
import com.baizhi.entity.Admin;
import com.baizhi.entity.CmfzLog;
import com.baizhi.utils.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAspect {
    private Logger logger= LoggerFactory.getLogger(LogAspect.class);
    @Autowired
    private CmfzLogMapper cmfzLogMapper;

    @Pointcut("@annotation(com.baizhi.annotation.AdminLogAnnotation)")
    public void logPoint(){

    }
    @After("logPoint()")
    public void Log(JoinPoint joinPoint){

        CmfzLog cmfzLog=new CmfzLog();

//        获取session
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
//        log_name
        cmfzLog.setAdminUsername(username);
        logger.debug(username);
//        log_date
        cmfzLog.setLogDate(new Date());
//        log_ip
        String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
        cmfzLog.setLogIp(ipAddrByRequest);
//        log_content
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AdminLogAnnotation annotation = method.getAnnotation(AdminLogAnnotation.class);
        String value = annotation.value();
        cmfzLog.setLogContent(value);

        cmfzLogMapper.insert(cmfzLog);
    }
}
